//
//  OauthViewController.swift
//  SinaWeiBo
//
//  Created by ZKJ on 2017/9/3.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {

    // MARK:- 控件的属性
    @IBOutlet weak var webView: UIWebView!
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置导航栏内容
        setUpOauthUI()
        
        // 加载网页
        loadWebView()
    }
}

// MARK:- 设置UI界面
extension OauthViewController {
    fileprivate func setUpOauthUI() {
        title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(OauthViewController.cancleClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OauthViewController.fillClick))
    }
    
    fileprivate func loadWebView() {
        // 1.获取登录页面的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        // 2.创建对应NSURL
        guard let url = URL(string: urlString) else {
            return
        }
        
        // 3.创建NSURLRequest对象
        let request = URLRequest(url: url)
        
        // 4.加载request对象
        webView.loadRequest(request)
    }
}

// MARK:- 监听点击事件
extension OauthViewController {
    @objc fileprivate func cancleClick() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func fillClick() {
        //1.添加js代码
        let jsCode = "document.getElementById('userId').value='13355939311';document.getElementById('passwd').value='Zkj@09.21.com_';"
        
        //2.执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}

// MARK:- 设置webView的代理
extension OauthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "正在加载...")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    // 当准备加载某一个页面时,会执行该方法
    // 返回值: true -> 继续加载该页面 false -> 不会加载该页面
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1.获取加载网页的NSURL
        guard let url = request.url else {
            return true
        }
        
        // 2.获取url中的字符串
        let urlString = url.absoluteString
        
        // 3.判断该字符串中是否包含code
        guard urlString.contains("code=") else {
            return true
        }
        print(urlString)
        
        // 4.将code截取出来
        let code = urlString.components(separatedBy: "code=").last!
        print(code)
        
        // 5.请求accessToken
        getAccessToken(code: code)
        
        return false
    }
}

extension OauthViewController {
    
    // MARK:- 获取access_token
    fileprivate func getAccessToken(code : String) {
        ZkjNetworkTool.shareInstance.requestToGetAccessToken(code: code) { (result, error) in
            if error != nil {
                print(error as Any)
            }
            
            guard let useDic = result else {
                print("用户授权数据获取失败")
                return
            }
            
            let user = UserInfo(dic: useDic)
            
            // 获取用户信息
            self.getUserInfo(userInfo: user)
        }
    }
    
    // MARK:- 获取用户登录信息
    fileprivate func getUserInfo(userInfo : UserInfo) {
        
        // 获取access_token
        guard let access_token = userInfo.access_token else {
            return;
        }
        
        // 获取uid
        guard let uid = userInfo.uid else {
            return
        }
        
        // 获取用户登录信息
        ZkjNetworkTool.shareInstance.requestToGetUserInfo(access_token: access_token, uid: uid) { (result, error) in
            if error != nil {
                print(error as Any)
                return
            }
            
            //拿到用户信息的结果
            guard let useDic = result else {
                print("获取用户信息失败")
                return
            }
            
            //从字典中取出昵称和用户头像地址
            userInfo.name = useDic["name"] as? String
            userInfo.avatar_hd = useDic["avatar_hd"] as? String
            print("userInfo : \(userInfo)")
            
            //将userInfo对象保存
            //归档
            NSKeyedArchiver.archiveRootObject(userInfo, toFile: UserInfoViewModel.sharInstance.userInfoPath)
            UserInfoViewModel.sharInstance.userInfo = userInfo
            print("-----------------")
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
        
    }
}








